// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.linqingying.gitcode.authentication.accounts

import com.intellij.collaboration.auth.AccountManagerBase
import com.intellij.collaboration.auth.AccountsRepository
import com.intellij.collaboration.auth.PasswordSafeCredentialsRepository
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.linqingying.gitcode.api.GitCodeServerPath
import com.linqingying.gitcode.util.GitCodeUtil

internal val GitCodeAccount.isGCAccount: Boolean get() = server.isGitCodeDotCom

/**
 * Handles application-level GitCode accounts
 */
@Service
class GCAccountManager : AccountManagerBase<GitCodeAccount, String>(logger<GCAccountManager>()), Disposable {

  override fun accountsRepository(): AccountsRepository<GitCodeAccount> = service<GCPersistentAccounts>()

  override fun credentialsRepository() =
    PasswordSafeCredentialsRepository<GitCodeAccount, String>(GitCodeUtil.SERVICE_DISPLAY_NAME,
                                                             PasswordSafeCredentialsRepository.CredentialsMapper.Simple)

  companion object {
    fun createAccount(name: String, server: GitCodeServerPath) = GitCodeAccount(name, server)
  }

  override fun dispose() = Unit

  fun isAccountUnique(server: GitCodeServerPath, accountName: String): Boolean {
    return accountsState.value.none { account: GitCodeAccount ->
      account.server.equals(server, true) && account.name == accountName
    }
  }
}
